package com.jiaquyun.jcyx.main

import androidx.lifecycle.Observer
import com.blankj.utilcode.util.BarUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.Cat
import com.jiaquyun.jcyx.entity.UserShops
import com.jiaquyun.jcyx.main.goods.GoodsScreenFragment
import com.jiaquyun.jcyx.main.goods.adapter.CateOneAdapter
import com.jiaquyun.jcyx.jetpack.mode.GoodsViewModel
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_main_cate.*

class MainCateFragment : OwnerViewModeFragment<GoodsViewModel>() {

    companion object {
        fun newInstance(): MainCateFragment {
            return MainCateFragment()
        }
    }

    private val cateOneAdapter: CateOneAdapter = CateOneAdapter()

    override val layoutResId: Int
        get() = R.layout.fragment_main_cate

    override fun viewModel(): GoodsViewModel {
        return createViewModel()
    }

    override fun initView() {
        BarUtils.addMarginTopEqualStatusBarHeight(flCategoryBar)

        //初始化一级分类视图
        rvCategoryTitle.adapter = cateOneAdapter

        cateOneAdapter.setOnItemClickListener { adapter, view, position ->
            cateOneAdapter.selectedPosition = position
            setChildFragmentManager(cateOneAdapter.getItem(position))
        }
    }

    override fun initData() {
        viewModel.goodsCategoryList()
    }

    override fun initViewMode() {
        viewModel.cateListLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.SUCCESS) {
                response.data?.data?.let {
                    cateOneAdapter.setNewInstance(it)
                }
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            val data = response.data?.data
            if (data.isNullOrEmpty())
                return@Observer
            cateOneAdapter.setNewInstance(data)
            setChildFragmentManager(cateEntity = data[0])
        })
    }

    private fun setChildFragmentManager(cateEntity: Cat) {
        childFragmentManager.beginTransaction().apply {
            replace(R.id.flCategoryGoods, GoodsScreenFragment.newInstance(cateEntity))
        }.commit()
    }

    override fun onEventMainThread(any: Any) {
        if (any is UserShops) {
            initData()
        }
    }
}